<template>
  <div class="component-index-img-add-or-update">
    <el-dialog
      v-model="visible"
      :title="!dataForm.imgId ? $t('crud.addTitle') : $t('temp.modify')"
      :close-on-click-modal="false"
      :width="dialogWidth"
      @close="onCloseDialogHandle"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        label-width="100px"
        @submit.prevent
      >
        <el-form-item
          :label="$t('admin.carouselImg')"
          prop="imgUrl"
          :label-width="labelWidth"
        >
          <div>
            <img-upload v-model="dataForm.imgUrl" />
            <span v-if="dataForm.imgType === 0">{{ $t('admin.recommImgSize') }}710*780</span>
            <span v-if="dataForm.imgType === 1">{{ $t('admin.recommImgSize') }}1920*450</span>
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('temp.sequence')"
          prop="seq"
          :label-width="labelWidth"
        >
          <el-input
            v-model="dataForm.seq"
            :min="0"
            type="number"
            oninput="if(value.length>3)value=value.slice(0,3)"
            on-keypress="return(/[\d\.]/.test(String.fromCharCode(event.keyCode)))"
            onkeyup="value=value.replace(/[^\d]/g,'')"
            @blur="onHandleSeq"
          />
        </el-form-item>
        <el-form-item
          :label="$t('product.status')"
          prop="status"
          :label-width="labelWidth"
        >
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="0">
              {{ $t('publics.disable') }}
            </el-radio>
            <el-radio :label="1">
              {{ $t('publics.normal') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="$t('platform.platform')"
          prop="imgType"
          :label-width="labelWidth"
        >
          <el-radio-group v-model="dataForm.imgType">
            <el-radio :label="0">
              {{ $t('platform.mobile') }}
            </el-radio>
            <el-radio :label="1">
              {{ $t('platform.pc') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="$t('publics.type')"
          prop="type"
          :label-width="labelWidth"
        >
          <div>
            <el-radio-group v-model="dataForm.type">
              <el-radio :label="-1">
                {{ $t('productComm.no') }}
              </el-radio>

              <el-radio :label="0">
                {{ $t('home.product') }}
              </el-radio>
            </el-radio-group>
            <div v-if="dataForm.type ===0 && dataForm.relation!=null">
              <el-card
                :body-style="{ padding: '0px' }"
                class="index-image-prod-card"
                style="height: 160px;width: 120px"
              >
                <prod-pic
                  height="104px"
                  width="100%"
                  :pic="card.pic"
                />
                <!-- todo: 商品已下架时展示状态 -->
                <div
                  v-if="false"
                  class="card-prod-status-tips"
                >
                  {{ $t('publics.hadLowerShelf') }}
                </div>
                <div class="card-prod-bottom">
                  <span class="card-prod-name">{{ card.name }}</span>
                  <div
                    class="card-prod-name-button default-btn text-btn"
                    @click="dataForm.relation = null"
                  >
                    {{ $t('text.delBtn') }}
                  </div>
                </div>
              </el-card>
            </div>
            <div v-if="dataForm.relation==null">
              <div
                v-if=" dataForm.type == 0"
                class="default-btn"
                @click="onAddProd"
              >
                {{ $t('product.select') }}
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div

          class="dialog-footer"
        >
          <div
            class="default-btn"
            @click="onClose()"
          >
            {{ $t('crud.filter.cancelBtn') }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="onSubmit()"
          >
            {{ $t('crud.filter.submitBtn') }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 商品选择弹窗-->
    <prods-select
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      :is-single="true"
      @refresh-select-prods="onSelectIndexProd"
    />
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const dataRule = reactive({
  imgUrl: [
    { required: true, message: $t('admin.carouselImgNoNull'), trigger: 'blur' }
  ],
  seq: [
    { required: true, message: $t('admin.sortNONull'), trigger: 'blur' }
  ]
})

const dialogWidth = ref('')
const defWidth = localStorage.getItem('bbcLang') === 'en' ? 500 : 500
const labelWidth = localStorage.getItem('bbcLang') === 'en' ? '140px' : '80px'
onMounted(() => {
  dialogWidth.value = setDialogWidth(defWidth)
  window.onresize = () => {
    return (() => {
      dialogWidth.value = setDialogWidth(defWidth)
    })()
  }
})
const setDialogWidth = function (defWidth) {
  const val = document.body.clientWidth
  const def = defWidth || 850 // 默认宽度
  if (val < def) {
    return '97%'
  } else {
    return def + 'px'
  }
}

// 获取分类数据
const dataFormRef = ref(null)
const dataForm = ref({
  status: 1,
  des: '',
  imgUrl: '',
  seq: 0,
  imgType: 0,
  imgId: 0,
  type: -1,
  relation: null
})
// 关联数据
const card = ref({
  id: 0,
  pic: '',
  name: '',
  realData: {
    prod: [],
    shop: [],
    activity: []
  }
})
const prodsSelectVisible = ref(false)
const visible = ref(false)
const init = (id) => {
  visible.value = true
  dataForm.value.imgId = id || 0
  nextTick(() => {
    prodsSelectVisible.value = false
    dataFormRef.value?.resetFields()
  })
  if (dataForm.value.imgId) {
    // 获取产品数据
    http({
      url: http.adornUrl(`/admin/indexImg/info/${dataForm.value.imgId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      if (data.relation) {
        card.value.pic = data.pic
        card.value.name = data.prodName
        card.value.id = data.relation
      }
    })
  } else {
    nextTick(() => {
      dataFormRef.value?.resetFields()
      dataForm.value.imgUrl = ''
    })
  }
}
// 表单提交
let isSubmit = true
const page = {
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
}
const onSubmit = () => {
  dataFormRef.value?.validate(() => {
    if (!dataForm.value.imgUrl) {
      return
    }
    if (!isSubmit) {
      return true
    }
    if (!dataForm.value.relation && dataForm.value.type !== -1) {
      ElMessage.error($t('marketing.pleaseSelectAProduct'))
      return
    }
    isSubmit = false
    const param = dataForm.value
    http({
      url: http.adornUrl('/admin/indexImg'),
      method: param.imgId ? 'put' : 'post',
      data: http.adornData(param)
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          isSubmit = true
          visible.value = false
          emit('refreshDataList', page)
        }
      })
    }).catch(e => {
      isSubmit = true
    })
  })
}

const onHandleSeq = () => {
  if (!dataForm.value.seq) {
    dataForm.value.seq = 0
  }
}

// 打开选择商品
const prodsSelectRef = ref(null)
const onAddProd = () => {
  prodsSelectVisible.value = true
  nextTick(() => {
    prodsSelectRef.value.init(card.value.realData.prod)
  })
}
// 添加指定商品
const onSelectIndexProd = (prods) => {
  card.value.realData.prods = [prods]
  if (prods) {
    const selectProd = prods
    dataForm.value.relation = selectProd.prodId
    card.value.pic = selectProd.pic
    card.value.name = selectProd.prodName
    card.value.id = selectProd.prodId
  } else {
    card.value = {}
  }
}
// 关闭对话框回调
const onCloseDialogHandle = () => {
  prodsSelectVisible.value = false
  dataFormRef.value?.resetFields()
  dataForm.value.relation = null
  card.value = {
    id: 0,
    pic: '',
    name: '',
    realData: {
      prod: [],
      shop: [],
      activity: []
    }
  }
}

/**
 * 关闭弹窗
 */
const onClose = () => {
  visible.value = false
}
defineExpose({
  init
})
</script>
<style lang="scss" scoped>
.component-index-img-add-or-update {
  .index-image-prod-card {
    position: relative;
    .card-prod-status-tips {
      position: absolute;
      right: 0;
      bottom: 54px;
      color: #fff;
      font-size: 12px;
      line-height: 16px;
      background-color:rgba(0, 0, 0, .3);
      padding: 3px 6px;
      border-top-left-radius: 4px;
    }
  }

  /* 卡片商品按钮样式*/
  .card-prod-bottom {
    position: relative;
    text-align: left;
    .card-prod-name {
      margin: auto;
      padding: 0 6px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 118px;
      display: inline-block;
    }
    .card-prod-name-button {
      position: absolute;
      top: 24px;
      right: 10px;
    }
  }
}
</style>
